package main

import (
	"fmt"
	"io/fs"
	"log"
	"os"
	"os/exec"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

var wg sync.WaitGroup
var runingThreadNum int64
var progress int64

func GetDirs(address string) []fs.DirEntry {
	dirs, _ := os.ReadDir(address)
	//返回
	return dirs
}

func ExecOrder(order string) (output []byte, err error) {
	cmd := exec.Command(order)
	output, err = cmd.CombinedOutput()
	return
}

func DeleteDir(dirPath string) {
	os.RemoveAll(dirPath)
	log.Println("delete " + dirPath)
}

func main() {

	order := "./AssetStudioCLI.exe"
	inputDirRoot := ""
	outputDir := ""
	args := []string{"--game", "BH3", "--group_assets", "ByContainer"}
	var threadNum int64 = 7

	if !strings.HasSuffix(inputDirRoot, "/") {
		inputDirRoot += "/"
	}
	dirs := GetDirs(inputDirRoot)
	inputModel := inputDirRoot + `%s`

	i := 0
	for i < len(dirs) {
		//控制线程数量
		if atomic.LoadInt64(&runingThreadNum) > threadNum {
			time.Sleep(time.Millisecond * 100)
			continue
		}
		//生成order
		inputDir := fmt.Sprintf(inputModel, dirs[i].Name())
		inputArgs := append([]string{inputDir, outputDir}, args...)
		wg.Add(1)
		atomic.AddInt64(&runingThreadNum, 1)
		go func(order string, args []string) {
			defer wg.Done()
			defer func() {
				atomic.AddInt64(&runingThreadNum, -1)
				fmt.Println(atomic.AddInt64(&progress, 1), "/", len(dirs))
				DeleteDir(args[0])
			}()

			cmd := exec.Command(order, args...)
			_, err := cmd.CombinedOutput()
			if err != nil {
				fmt.Println(err)
				return
			}
		}(order, inputArgs)
		i++
	}
	wg.Wait()
}